package com.shouhuobao.take.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import droid.frame.utils.android.Alert;

/**
 * 图片下载保存到相册
 *
 * @author joker<br>
 *         2016-12-5下午3:33:28
 */
public class ImageDownUtils {

    private Context mContext;

    private Handler mHandler = new Handler();

    public ImageDownUtils(Context context) {
        mContext = context;
    }

    private ProgressDialog pBar;

    public void downImageFile(final String url) {
        pBar = new ProgressDialog(mContext);
        pBar.setTitle("请稍候……");
        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pBar.setCancelable(false);
        downFile(url);
    }

    private void downFile(final String url) {
        pBar.show();
        new Thread() {
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL urlPath = new URL(url);
                    connection = (HttpURLConnection) urlPath.openConnection();
                    connection.setConnectTimeout(20000);
                    connection.connect();
                    double length = connection.getContentLength();
                    InputStream is = connection.getInputStream();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File appDir = new File(Environment.getExternalStorageDirectory(), "take");
                        if (!appDir.exists()) {
                            appDir.mkdir();
                        }
                        File file = new File(appDir, url.substring(url.lastIndexOf("/") + 1, url.length()));
                        fileOutputStream = new FileOutputStream(file);
                        byte[] buf = new byte[1024];
                        int ch = -1;
                        double count = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                            int i = (int) (count / length * 100);
                            pBar.setProgress(i);
                        }
                        MediaStore.Images.Media.insertImage(mContext.getContentResolver(), file.getPath(), file.getName(), "description");
                        // 最后通知图库更新
                        mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                    down();
                } catch (IOException e) {
                    down();
                    Alert.toast("下载失败");
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }.start();
    }

    public void down() {
        mHandler.post(new Runnable() {
            public void run() {
                pBar.cancel();
                Alert.toast("下载成功");
            }
        });
    }

}
